<script src="../../../api/system/user.js"></script>
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--证书类型-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="credentialsType"
            placeholder="证书类型"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="credentialsTypeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="用户姓名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户姓名"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="证书状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['credentials:credentials:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['credentials:credentials:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['credentials:credentials:remove']"
            >删除
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="credentialsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="证书编号" align="center" hidden prop="credentialsId"/>
          <el-table-column label="证书类型" align="center" hidden prop="credentialsType"/>
          <el-table-column label="所属用户" align="center" prop="userName"/>
          <el-table-column label="证书" align="center" prop="credentialsName">　
            <template scope="scope">
              <el-image v-for="item in scope.row.credentialsName==null?'':scope.row.credentialsName.split(',')"
                        style="width: 40px; height: 40px"
                        :src="'http://localhost/dev-api'.concat(item)"
                        :preview-src-list="['http://localhost/dev-api'.concat(item)]">
              </el-image>
            </template>
          </el-table-column>
          <!--          <el-table-column label="证书状态" align="center" prop="status"/>-->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['credentials:credentials:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['credentials:credentials:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改用户证书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="证书类型" prop="credentialsTypeId">
              <treeselect v-model="form.credentialsTypeId" :options="credentialsTypeTreeOptions"
                          :normalizer="normalizerCds" placeholder="选择证书类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" @select="getUser($event)"
                          :normalizer="normalizer" placeholder="选择部门"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择用户" prop="userId">
              <el-select v-model="form.userId" clearable placeholder="选择用户">
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="证书上传" prop="form">
              <el-upload ref="upload"
                         action="http://localhost/dev-api/uploadFile"
                         list-type="picture-card"
                         name="file"
                         :file-list="fileList"
                         accept="image/png, image/jpeg"
                         :with-credentials="credentials"
                         :limit="limit"
                         :headers="headers"
                         :on-preview="handlePictureCardPreview"
                         :on-success="handlePictureSuccess"
                         :on-error="handlePictureSuccess"
                         :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>

            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listCredentials,
    getCredentials,
    delCredentials,
    addCredentials,
    updateCredentials,
    exportCredentials
  } from "@/api/credentials/credentials";
  import {treeselect, listCredentialsType} from "@/api/system/credentialsType";
  import {listDept} from "@/api/system/dept";
  import {listUser} from "@/api/system/user";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "Credentials",
    components: {Treeselect},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 用户证书表格数据
        credentialsList: [],
        // 弹出层标题
        title: "",
        limit: 2,
        credentials: true,
        // 是否显示弹出层
        open: false,
        dialogImageUrl: '',
        dialogVisible: false,
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 证书类型选项
        credentialsTypeOptions: undefined,
        credentialsType: undefined,
        credentialsTypeTreeOptions: [],
        // 部门树
        deptOptions: undefined,
        // 日期范围
        dateRange: [],
        fileList: [],
        // 状态数据字典
        statusOptions: [],
        headers: {
          "Access-Control-Allow-Origin": "http://localhost,http://localhost:8080,*"
        },
        deptId: undefined,
        userList: undefined,
        userOptions: undefined,
        userName: undefined,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          credentialsTypeId: undefined,
          userId: undefined,
          credentialsName: undefined,
          status: undefined,
          deptId: undefined
        },
        images: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          credentialsTypeId: [
            {required: true, message: "证书类型不能为空", trigger: "blur"}
          ],
          deptId: [
            {required: true, message: "部门不能能为空", trigger: "blur"}
          ],
          userId: [
            {required: true, message: "用户不能能为空", trigger: "blur"}
          ],

        }
      };
    },
    created() {
      this.getList();
      this.getTreeselect();
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
    },
    watch: {
      // 根据名称筛选部门树
      credentialsType(val) {
        this.$refs.tree.filter(val);
      }
    },
    methods: {
      /** 查询用户证书列表 */
      getList() {
        this.loading = true;
        listCredentials(this.queryParams).then(response => {
          this.credentialsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        for (var i in this.fileList) {
          if (this.fileList[i].uuid == file.uuid) {
            var count = --i;
            this.fileList.splice(count, 1);
            this.images.splice(count, 1);
            this.form.credentialsName = this.images.toString();
          }
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handlePictureSuccess(response, file, fileList) {
        if (response.code == 200) {
          var imgurl = response.data;
          var params = {
            "url": "http://localhost/dev-api" + imgurl
          }
          this.fileList.push(params);
          this.images.push(imgurl);
          this.form.credentialsName = this.images.toString();
        }
      },
      handlePictureFail(response, file, fileList) {

      },
      beforeRemove() {

      },
      /** 查询证书下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.credentialsTypeOptions = this.handleTree(response.data, "credentialsTypeId");
        });
      },

      /** 查询部门下拉树结构 */
      getCTTreeselect() {
        listCredentialsType().then(response => {
          this.credentialsTypeTreeOptions = this.handleTree(response.data, "credentialsTypeId");
          console.log(this.credentialsTypeTreeOptions)
        });
      },
      /** 查询部门下拉树结构 */
      getDeptTreeselect() {
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
          console.log(this.deptOptions)
        });
      },
      /** 部门下的用户 */
      getUser(node) {
        // 获取部门id
        console.log(node.deptId);
        var temp = {};
        temp.deptId = node.deptId;
        // 查询部门下的用户
        listUser(temp).then(response => {
          this.userOptions = response.rows;
        });
        this.userName = "";


      },
      /** 转换部门数据结构 */
      normalizer(node) {

        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        };
      },
      /** 转换部门数据结构 */
      normalizerCds(node) {

        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.credentialsTypeId,
          label: node.credentialsType,
          children: node.children
        };
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.fileList = []
      },
      // 表单重置
      reset() {
        this.form = {
          credentialsId: undefined,
          credentialsTypeId: undefined,
          userId: undefined,
          credentialsName: undefined,
          status: "0",
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.credentialsId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.dialogImageUrl = "";
        this.getDeptTreeselect()
        this.getCTTreeselect();
        this.open = true;
        this.fileList = []
        this.images = []
        this.title = "上传用户证书";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getDeptTreeselect()
        this.getCTTreeselect();

        var array = row.credentialsName.split(",");
        for (var i = 0; i < array.length; i++) {
          this.fileList.push({"url": "http://localhost/dev-api" + array[i]})
        }
        const credentialsId = row.credentialsId || this.ids
        getCredentials(credentialsId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改用户证书";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.credentialsId != undefined) {
              updateCredentials(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addCredentials(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const credentialsIds = row.credentialsId || this.ids;
        this.$confirm('是否确认删除用户证书编号为"' + credentialsIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delCredentials(credentialsIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有用户证书数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportCredentials(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      // 节点单击事件,获取证书
      handleNodeClick(data) {
        console.log(data)
        this.queryParams.credentialsTypeId = data.id;
        this.getList();
      },
    }
  };
</script>
